//
//  SPSignInViewController.m
//  SuperPatrner
//
//  Created by EvanZ on 15/3/15.
//  Copyright (c) 2015年 EvanZ. All rights reserved.
//

#import "SPSignInViewController.h"
#import "UIColor+CreateMethod.h"
#import "SPHTTPRequestOperationManager.h"
#import "Methods.h"
#import "Define.h"

@interface SPSignInViewController (){
    UITextField * m_usernameField;
    UITextField * m_nicknameField;
    UITextField * m_passwordField;
    UITextField * m_comfirmPasswordField;
    UITextField * m_codeField;
    UITextField * m_verificationCodeField;
    float leftoffset;
    UIScrollView * m_scrollView;
    UIButton * m_sendVerificationCodeButton;
    NSString * m_verificationCode;
}

@end

@implementation SPSignInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    leftoffset = 50;
    
    CGRect frame = self.view.frame;
    frame.origin.y -= 20;
    m_scrollView = [[UIScrollView alloc]initWithFrame:frame];
    m_scrollView.showsHorizontalScrollIndicator = NO;
    m_scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:m_scrollView];
    
    UIImage * bgImage = [UIImage imageNamed:@"login_bg"];
    UIImageView * bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width/bgImage.size.width*bgImage.size.height)];
    [bgImageView setImage:bgImage];
    [m_scrollView addSubview:bgImageView];
    
    UIImageView * iconView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 75, 75)];
    [iconView setImage:[UIImage imageNamed:@"logo_icon"]];
    [iconView setCenter:CGPointMake(bgImageView.center.x, bgImageView.center.y-10)];
    [m_scrollView addSubview:iconView];
    
    UITextField * titleField = [[UITextField alloc]initWithFrame:CGRectMake(80, iconView.frame.origin.y + iconView.frame.size.height + 10, self.view.frame.size.width-60, 30)];
    [titleField setBackgroundColor:[UIColor clearColor]];
    [titleField setText:@"凝聚人才，共享财富"];
    [titleField setTextColor:[UIColor whiteColor]];
    [titleField setFont:[UIFont boldSystemFontOfSize:18]];
    [titleField setEnabled:NO];
    [m_scrollView addSubview:titleField];
    
    m_usernameField = [[UITextField alloc]initWithFrame:CGRectMake(leftoffset, bgImageView.frame.origin.y + bgImageView.frame.size.height + 20, self.view.frame.size.width - 2*leftoffset, 30)];
    [m_usernameField setBackgroundColor:[UIColor clearColor]];
    [m_usernameField setPlaceholder:@"手机号"];
    m_usernameField.delegate = self;
    [m_scrollView addSubview:m_usernameField];
    
    UIImageView * usernameIcon = [[UIImageView alloc]initWithFrame:CGRectMake(20, m_usernameField.frame.origin.y, 20, 20)];
    [usernameIcon setImage:[UIImage imageNamed:@"login_user_icon"]];
    [m_scrollView addSubview:usernameIcon];
    
    m_nicknameField = [[UITextField alloc]initWithFrame:CGRectMake(leftoffset, m_usernameField.frame.origin.y + m_usernameField.frame.size.height + 20, self.view.frame.size.width - 2*leftoffset, 30)];
    [m_nicknameField setBackgroundColor:[UIColor clearColor]];
    m_nicknameField.delegate = self;
    [m_nicknameField setPlaceholder:@"昵称"];
    [m_scrollView addSubview:m_nicknameField];
    
    UIImageView * nicknameIcon = [[UIImageView alloc]initWithFrame:CGRectMake(20, m_nicknameField.frame.origin.y, 20, 20)];
    [nicknameIcon setImage:[UIImage imageNamed:@"login_user_icon"]];
    [m_scrollView addSubview:nicknameIcon];
    
    m_passwordField = [[UITextField alloc]initWithFrame:CGRectMake(leftoffset, m_nicknameField.frame.origin.y + m_nicknameField.frame.size.height + 20, self.view.frame.size.width - 2*leftoffset, 30)];
    [m_passwordField setBackgroundColor:[UIColor clearColor]];
    [m_passwordField setPlaceholder:@"密码"];
    m_passwordField.delegate = self;
    [m_scrollView addSubview:m_passwordField];
    
    UIImageView * paswordIcon = [[UIImageView alloc]initWithFrame:CGRectMake(20, m_passwordField.frame.origin.y, 20, 20)];
    [paswordIcon setImage:[UIImage imageNamed:@"login_password_icon"]];
    [m_scrollView addSubview:paswordIcon];
    
    m_comfirmPasswordField = [[UITextField alloc]initWithFrame:CGRectMake(leftoffset, m_passwordField.frame.origin.y + m_passwordField.frame.size.height + 20, self.view.frame.size.width - 2*leftoffset, 30)];
    [m_comfirmPasswordField setBackgroundColor:[UIColor clearColor]];
    [m_comfirmPasswordField setPlaceholder:@"确认密码"];
    m_comfirmPasswordField.delegate = self;
    [m_scrollView addSubview:m_comfirmPasswordField];
    
    UIImageView * paswordComfirmIcon = [[UIImageView alloc]initWithFrame:CGRectMake(20, m_comfirmPasswordField.frame.origin.y, 20, 20)];
    [paswordComfirmIcon setImage:[UIImage imageNamed:@"login_password_icon"]];
    [m_scrollView addSubview:paswordComfirmIcon];
    
    m_codeField = [[UITextField alloc]initWithFrame:CGRectMake(leftoffset, m_comfirmPasswordField.frame.origin.y + m_comfirmPasswordField.frame.size.height + 20, self.view.frame.size.width - 2*leftoffset, 30)];
    [m_codeField setBackgroundColor:[UIColor clearColor]];
    [m_codeField setPlaceholder:@"邀请码"];
    m_codeField.delegate = self;
    [m_scrollView addSubview:m_codeField];
    
    UIButton * scanButton = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-40, m_codeField.frame.origin.y, 20, 20)];
    [scanButton setBackgroundImage:[UIImage imageNamed:@"signin_scan"] forState:UIControlStateNormal];
    [scanButton addTarget:self action:@selector(scanButtonListener) forControlEvents:UIControlEventTouchUpInside];
    [m_scrollView addSubview:scanButton];
    
    UIImageView * codeIcon = [[UIImageView alloc]initWithFrame:CGRectMake(20, m_codeField.frame.origin.y, 20, 20)];
    [codeIcon setImage:[UIImage imageNamed:@"signin_code"]];
    [m_scrollView addSubview:codeIcon];
    
    m_verificationCodeField = [[UITextField alloc]initWithFrame:CGRectMake(leftoffset, m_codeField.frame.origin.y + m_codeField.frame.size.height + 20, self.view.frame.size.width - 2*leftoffset, 30)];
    [m_verificationCodeField setBackgroundColor:[UIColor clearColor]];
    [m_verificationCodeField setPlaceholder:@"验证码"];
    m_verificationCodeField.delegate = self;
    [m_scrollView addSubview:m_verificationCodeField];
    
    UIImageView * veriIcon = [[UIImageView alloc]initWithFrame:CGRectMake(20, m_verificationCodeField.frame.origin.y, 20, 20)];
    [veriIcon setImage:[UIImage imageNamed:@"login_password_icon"]];
    [m_scrollView addSubview:veriIcon];
    
    m_sendVerificationCodeButton = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width -70- leftoffset, m_verificationCodeField.frame.origin.y , 100, 30)];
    [m_sendVerificationCodeButton setBackgroundImage:[UIImage imageNamed:@"veri_code_btn"] forState:UIControlStateNormal];
    [m_sendVerificationCodeButton setTitle:@"获取短信验证码" forState:UIControlStateNormal];
    m_sendVerificationCodeButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [m_sendVerificationCodeButton addTarget:self action:@selector(sendVerificationCodeButtonListener) forControlEvents:UIControlEventTouchUpInside];
    [m_scrollView addSubview:m_sendVerificationCodeButton];
    
    UIButton * signinButton = [[UIButton alloc]initWithFrame:CGRectMake(0, m_verificationCodeField.frame.origin.y + m_verificationCodeField.frame.size.height + 20, self.view.frame.size.width, 40)];
    [signinButton setBackgroundImage:[UIImage imageNamed:@"login_login_btn"] forState:UIControlStateNormal];
    [signinButton setTitle:@"注册" forState:UIControlStateNormal];
    [signinButton addTarget:self action:@selector(signinButtonListener) forControlEvents:UIControlEventTouchUpInside];
    [m_scrollView addSubview:signinButton];
    
    UIButton * backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, signinButton.frame.origin.y + signinButton.frame.size.height + 10, self.view.frame.size.width, 40)];
    [backButton setTitle:@"返回登录" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor colorWith8BitRed:122 green:177 blue:226 alpha:1] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonListener) forControlEvents:UIControlEventTouchUpInside];
    [m_scrollView addSubview:backButton];
    
    [m_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, backButton.frame.origin.y + backButton.frame.size.height)];
    
    UITapGestureRecognizer *tapBg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignTextField)];
    tapBg.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapBg];
}

- (void)resignTextField
{
    [m_usernameField resignFirstResponder];
    [m_nicknameField resignFirstResponder];
    [m_passwordField resignFirstResponder];
    [m_comfirmPasswordField resignFirstResponder];
    [m_codeField resignFirstResponder];
    [m_verificationCodeField resignFirstResponder];
}

#pragma mark - button listeners

- (void)sendVerificationCodeButtonListener{
    if (m_usernameField.text.length == 0) {
        [self showHintProgressWithText:@"请输入手机号"];
    }
    else if ([Methods isExistenceNetwork]) {
        [self verificationCode];
        [m_sendVerificationCodeButton setEnabled:NO];    }
    else{
        [self showHintProgressWithText:@"无可用网络"];
    }
}

- (void)backButtonListener{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)signinButtonListener{
    if (m_usernameField.text.length == 0) {
        [self showHintProgressWithText:@"请输入用户名"];
    }
    else if (m_nicknameField.text.length == 0){
        [self showHintProgressWithText:@"请输入昵称"];
    }
    else if (m_passwordField.text.length == 0){
        [self showHintProgressWithText:@"请输入密码"];
    }
    else if (m_comfirmPasswordField.text.length == 0){
        [self showHintProgressWithText:@"请输入确认密码"];
    }
    else if (![m_passwordField.text isEqualToString:m_comfirmPasswordField.text]){
        [self showHintProgressWithText:@"确认密码与密码不一致"];
    }
    else if (m_codeField.text.length == 0){
        [self showHintProgressWithText:@"请输入邀请码"];
    }
    else if (m_verificationCodeField.text.length == 0){
        [self showHintProgressWithText:@"请输入验证码"];
    }
    else if (![m_verificationCodeField.text isEqualToString:m_verificationCode]){
        [self showHintProgressWithText:@"验证码不正确，请重新获取"];
    }
    else{
        if ([Methods isExistenceNetwork]) {
            [self signin];
        }
        else{
            [self showHintProgressWithText:@"无可用网络"];
        }
    }
}

- (void)scanButtonListener{
    ZBarReaderViewController *reader = [ZBarReaderViewController new];
    reader.readerDelegate = self;
    reader.supportedOrientationsMask = ZBarOrientationMaskAll;

    ZBarImageScanner *scanner = reader.scanner;
    
    // TODO: (optional) additional reader configuration here
    
    // EXAMPLE: disable rarely used I2/5 to improve performance
    [scanner setSymbology: ZBAR_I25
                   config: ZBAR_CFG_ENABLE
                       to: 0];
    
    // present and release the controller
    [self presentViewController:reader animated:YES completion:nil];
}

- (void)signin{
    [self showProgressAutoCloseInNetwork:@"注册中，请稍后"];
    NSDictionary * para = [[NSDictionary alloc]initWithObjectsAndKeys:m_usernameField.text,@"phone",[Methods md5:m_passwordField.text],@"password",m_nicknameField.text,@"account_name",m_codeField.text,@"invitation_code", nil];
    SPHTTPRequestOperationManager *manager = [SPHTTPRequestOperationManager manager];
    [manager signinPara:para Success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"signin>>>>>>>>SUCCESS: %@\nmessage:%@",responseObject,[responseObject valueForKey:@"message"]);
        
        if ([[responseObject valueForKey:@"is_success"] intValue] != 0) {
            [[NSUserDefaults standardUserDefaults]setValue:[responseObject valueForKey:@"user_id"] forKey:@"user_id"];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        else{
            [self closeProgress];
            [self showHintProgressWithText:[responseObject valueForKey:@"message"]];
        }
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"signin>>>>>>>>Error: %@", error);
        [self showHintProgressWithText:@"注册失败"];

    }];
}

- (void)verificationCode{
    NSDictionary * para = [[NSDictionary alloc]initWithObjectsAndKeys:m_usernameField.text,@"phone", nil];
    SPHTTPRequestOperationManager *manager = [SPHTTPRequestOperationManager manager];
    [manager  sendSigninVerificationCodePara:para Success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"send_verification_code>>>>>>>>SUCCESS: %@\nmessage:%@",responseObject,[responseObject valueForKey:@"message"]);
        
        if ([[responseObject valueForKey:@"is_success"] intValue] == 1) {
            [self showHintProgressWithText:@"短信验证码申请已发送"];
            m_verificationCode = [NSString stringWithString:[responseObject valueForKey:@"phone_code"]];
        }
        else{
            [self showHintProgressWithText:[responseObject valueForKey:@"message"]];
            [m_sendVerificationCodeButton setEnabled:YES];
        }
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"send_verification_code>>>>>>>>Error: %@", error);
        [self closeProgress];
        [self showHintProgressWithText:@"邀请码发送失败"];
        [m_sendVerificationCodeButton setEnabled:YES];
    }];
}

#pragma mark - imagepicker delegate
- (void) imagePickerController: (UIImagePickerController*) reader
 didFinishPickingMediaWithInfo: (NSDictionary*) info
{
    // ADD: get the decode results
    id<NSFastEnumeration> results =
    [info objectForKey: ZBarReaderControllerResults];
    ZBarSymbol *symbol = nil;
    for(symbol in results)
        break;
    
    // EXAMPLE: do something useful with the barcode data
    m_codeField.text = symbol.data;
   
    [reader dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - textfield delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    float offset = - 100.0f;
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard"context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    CGRect rect = CGRectMake(0.0f, offset , width, height);
    self.view.frame = rect;
    [UIView commitAnimations];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard"context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    CGRect rect = CGRectMake(0.0f, 0.0 , width, height);
    self.view.frame = rect;
    [UIView commitAnimations];
}

@end
